import { useActiveThreadId } from "@renderer/queries";
import { useChatParametersByThreadId } from "@renderer/queries/hooks/use-thread-forms";
import { CHAT_PARAMETERS_CACHE_KEY } from "@shared/constants";
import logger from "@shared/logger/renderer-logger";
import type { ThreadFormChatParameters } from "@shared/triplit/types";
import { useCallback, useMemo } from "react";

type NonNullChatParams = Exclude<ThreadFormChatParameters, null>;

const defaultChatParameters: NonNullChatParams = {
  temperature: null,
  topP: null,
  maxTokens: null,
  presencePenalty: null,
  frequencyPenalty: null,
  numberOfHistoricalContext: null,
  autoabstractContext: null,
  abstractPrompt: null,
  systemPrompt: null,
  userPromptTemplate: null,
};

const { threadFormsService } = window.service;

export function useChatParameters(initial?: Partial<NonNullChatParams>) {
  const { data: activeThreadId } = useActiveThreadId();
  const { data: threadFormsChatParameters } =
    useChatParametersByThreadId(activeThreadId);

  const mergedDefaults = useMemo(
    () => ({ ...defaultChatParameters, ...(initial ?? {}) }),
    [initial],
  );

  const setParam = useCallback(
    async <K extends keyof NonNullChatParams>(
      key: K,
      value: NonNullChatParams[K],
    ) => {
      const { isOk, errorMsg } =
        await threadFormsService.updateChatParametersByThreadId(
          activeThreadId ?? CHAT_PARAMETERS_CACHE_KEY,
          {
            chatParameters: {
              ...threadFormsChatParameters,
              [key]: value,
            },
          },
        );

      if (!isOk) {
        logger.error("useChatParameters:setParam error", {
          error: errorMsg,
        });
      }
    },
    [activeThreadId, threadFormsChatParameters],
  );

  return {
    params: {
      ...mergedDefaults,
      ...(threadFormsChatParameters ?? {}),
    } as NonNullChatParams,
    setParam,
  };
}
